const sqlite3 = require('sqlite3').verbose();
const bcrypt = require('bcrypt'); // 引入bcrypt库用于密码加密和验证
const db = new sqlite3.Database('file_management.db');
module.exports = db;

db.serialize(() => {
    db.run('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE, password_hash TEXT)'); // 将password字段改为password_hash，用于存储加密后的密码
    const users = [
        { username: 'zs', password: 'ddd' },
        { username: 'ls', password: 'ddd' }
    ];
    const stmt = db.prepare('INSERT OR IGNORE INTO users (username, password_hash) VALUES (?,?)');
    users.forEach(user => {
        bcrypt.hash(user.password, 10, (err, hash) => { // 对密码进行加密，10是加密的成本因子，可以根据实际情况调整
            if (err) {
                console.error(err);
                return;
            }
            stmt.run(user.username, hash);
        });
    });
    stmt.finalize();
});

function authenticateUser(username, password, callback) {
    db.get('SELECT password_hash FROM users WHERE username =?', [username], (err, row) => {
        if (err) return callback(err);
        if (!row) return callback(null, false);
        bcrypt.compare(password, row.password_hash, (err, result) => { // 比对输入密码和数据库中加密后的密码
            if (err) return callback(err);
            callback(null, result);
        });
    });
}

module.exports.authenticateUser = authenticateUser;